package com.taoym.voucher.common.utils;

import com.taoym.voucher.common.response.ResponseStatusCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 * @author: taoym
 * @date: 2021/4/6 10:12
 * @desc: httpClient网络请求工具类
 */
@Slf4j
public class HttpClientUtils {

    private static final String GET = "get";
    private static final String POST = "post";
    private static final String REQUEST_HEADER_CONNECTION = "keep-alive";
    private static final String REQUEST_HEADER_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36";


    public static String doGet(String url) {
        return createRequest(url, GET, null);
    }

    public static String doPost(String url, String data) {
        return createRequest(url, POST, data);
    }

    /**
     * @author: taoym
     * @date: 2021/4/6 10:17
     * @desc: 创建请求
     */
    private static String createRequest(String url, String method, String data) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        try {
            if (GET.equals(method)) {
                HttpGet httpGet = new HttpGet(url);
                httpGet.setHeader("Connection", REQUEST_HEADER_CONNECTION);
                httpGet.setHeader("User-Agent", REQUEST_HEADER_USER_AGENT);
                response = httpClient.execute(httpGet);
            } else if (POST.equals(method)) {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Connection", REQUEST_HEADER_CONNECTION);
                httpPost.setHeader("User-Agent", REQUEST_HEADER_USER_AGENT);
                httpPost.addHeader("content-type", "application/json;charset=utf-8");
                httpPost.addHeader("accept", "application/json");
                // 有参数进来
                if (!ObjectUtils.isEmpty(data)) {
                    httpPost.setEntity(new StringEntity(data, "UTF-8"));
                }
                response = httpClient.execute(httpPost);
            }
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionCore(ResponseStatusCode.NET_IS_WRONG);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
